package io.github.wslxm.springbootplus2.manage.sys.dao.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.github.wslxm.springbootplus2.core.base.service.impl.BaseServiceImpl;
import io.github.wslxm.springbootplus2.manage.sys.dao.SysRoleUserDao;
import io.github.wslxm.springbootplus2.manage.sys.mapper.SysRoleUserMapper;
import io.github.wslxm.springbootplus2.manage.sys.model.entity.SysRoleUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangsong
 */
@Service
public class SysRoleUserDaoImpl extends BaseServiceImpl<SysRoleUserMapper, SysRoleUser> implements SysRoleUserDao {


    @Override
    public List<String> findRoleIdsByUserId(String userId) {
        List<SysRoleUser> list = this.list(new LambdaQueryWrapper<SysRoleUser>().eq(SysRoleUser::getUserId, userId));
        return list.stream().map(SysRoleUser::getRoleId).toList();
    }

    @Override
    public List<String> findUserIdsByRoleId(String roleId) {
        List<SysRoleUser> list = this.list(new LambdaQueryWrapper<SysRoleUser>().eq(SysRoleUser::getRoleId, roleId));
        return list.stream().map(SysRoleUser::getUserId).toList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updUserRole(String userId, List<String> roleIds) {
        // 删除用户的所有角色
        this.remove(new LambdaQueryWrapper<SysRoleUser>().eq(SysRoleUser::getUserId, userId));
        if (roleIds == null || roleIds.size() <= 0) {
            return true;
        }
        // 设置新的角色
        List<SysRoleUser> roleUserList = new ArrayList<>();
        roleIds.forEach(roleId -> roleUserList.add(new SysRoleUser(roleId, userId)));
        return this.saveBatch(roleUserList, 1024);
    }


    @Override
    public boolean delByUserId(String userId) {
        return this.remove(new LambdaQueryWrapper<SysRoleUser>().eq(SysRoleUser::getUserId, userId));
    }

    @Override
    public boolean delByRoleId(String roleId) {
        return this.remove(new LambdaQueryWrapper<SysRoleUser>().eq(SysRoleUser::getRoleId, roleId));
    }

}
